﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Management;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace DaFunction
{
    public class Fingerprint
    {
        /// <summary>
        /// 获得设备指纹
        /// </summary>
        /// <returns></returns>
        public static String GetFingerprint()
        {
            String finger = "";
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
                foreach (ManagementObject mo in searcher.Get())
                {
                    object moItem = mo["SerialNumber"];
                    String moString = "";
                    if (moItem == null)
                    {
                        moString = GetDiskID();
                        if (moString == "")
                        {
                            moString = "7E0220010372";
                        }

                    }
                    else
                    {
                        moString = moItem.ToString().Trim();
                    }
                    byte[] result = Encoding.Default.GetBytes(moString);
                    MD5 md5 = new MD5CryptoServiceProvider();
                    byte[] output = md5.ComputeHash(result);
                    finger = Convert.ToBase64String(output);
                    break;
                }
                searcher.Dispose();
            }
            catch (Exception ex)
            {
                
            }
            return finger;
        }

        [System.Runtime.InteropServices.DllImport("DiskID32.dll")]
        private static extern long DiskID32(ref byte DiskModel, ref byte DiskID);
        private static string GetDiskID()
        {
            byte[] DiskModel = new byte[31];
            byte[] DiskID = new byte[31];
            int i;
            string ID = "";
            if (DiskID32(ref DiskModel[0], ref DiskID[0]) != 1)
            {
                for (i = 0; i < 31; i++)
                {
                    if (Convert.ToChar(DiskID[i]) != Convert.ToChar(0))
                    {
                        ID = ID + Convert.ToChar(DiskID[i]);
                    }
                }
                ID = ID.Trim();
            }
            else
            {
                Console.WriteLine("获得设备指纹错误");
            }
            return ID;
        }
    }
}
